const base = require("./../base");
const fse = require("fs-extra");
const fs = require("fs");

module.exports = class extends base {
    async _initialize() {
        await super.isWxaAuth();
    }

    /**
     *
     * @api {get} /home/pay/wxpay/index 获取微信支付配置
     * @apiDescription 获取微信支付配置
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} WxaToken 小程序授权token
     *
     * @apiSampleRequest /home/pay/wxpay/index
     */
    async index() {
        const wxaId = this.state.wxa.id;
        const wxaPay = await this.model("wxa_pay")
            .query(qb => {
                qb.where("wxa_id", wxaId);
            })
            .fetch();
        this.success(wxaPay);
    }

    /**
     *
     * @api {post} /home/pay/wxpay/add 修改微信支付配置
     * @apiDescription 修改微信支付配置
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} WxaToken 小程序授权token
     *
     * @apiParam {String} mchid 商户号
     * @apiParam {String} key 商户秘钥
     * @apiParam {String} pfx 支付证书
     *
     * @apiSampleRequest /home/pay/wxpay/add
     */
    async add() {
        const { mchid, key, pfx } = this.post;
        const wxaId = this.state.wxa.id;

        let wxaPay = await this.model("wxa_pay")
            .query(qb => {
                qb.where("wxa_id", wxaId);
            })
            .fetch();

        const data = { mchid: mchid, key: key, pfx: pfx };
        if (wxaPay) {
            wxaPay = await this.model("wxa_pay")
                .forge(
                    Object.assign(
                        {
                            id: wxaPay.id
                        },
                        data
                    )
                )
                .save();
        } else {
            wxaPay = await this.model("wxa_pay")
                .forge(
                    Object.assign(
                        {
                            wxa_id: this.state.wxa.id
                        },
                        data
                    )
                )
                .save();
        }
        this.success(wxaPay);
    }

    /**
     *
     * @api {post} /home/pay/wxpay/upload_cert 上传解析微信支付证书
     * @apiDescription 上传解析微信支付证书
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} WxaToken 小程序授权token
     *
     * @apiParam {String} file 微信支付证书
     *
     * @apiSampleRequest /home/pay/wxpay/upload_cert
     */
    async upload_cert() {
        const { file } = this.file;
        if (
            file.type !== "application/x-pkcs12" &&
            file.name !== "apiclient_cert.p12"
        ) {
            await fsp.remove(file.path);
            return;
        }

        const pfx = JSON.stringify(fs.readFileSync(file.path));
        await fse.remove(file.path);

        this.success(pfx);
    }
};
